/* eslint-disable no-console */
const axios = require('axios')

const fs = require('fs')
const path = require('path')
const yaml = require('js-yaml') // 引入js-yaml库

// 获取当前脚本所在目录的上级目录
const parentDir = path.dirname(__dirname)
const configFilePath = path.join(parentDir, 'local_config.yaml')
// 读取YAML配置文件
const configData = fs.readFileSync(configFilePath, 'utf8')
const config = yaml.safeLoad(configData) // 使用js-yaml的safeLoad方法解析YAML字符串

let Sid
let gorillaCsrfValue
let xHarborCsrfToken

const harborLogin = async (ctx, next) => {
  try {
    // 执行发送HTTP登录请求的函数
    const response = await sendHarborLoginRequest()

    const setCookieHeader = response.headers['set-cookie']
    // 使用正则表达式提取第二个sid的值
    const regex = /sid=([^;]+)/g
    let match
    const sidValues = []
    // eslint-disable-next-line no-cond-assign
    while ((match = regex.exec(setCookieHeader)) !== null) {
      if (match.index === regex.lastIndex) {
        regex.lastIndex++
      }

      // 第一个匹配是整个正则表达式，第二个匹配是括号内的内容
      if (match.length >= 2) {
        sidValues.push(match[1])
      }
    }

    // 如果找到至少两个sid值，则存储起来
    if (sidValues.length >= 2) {
      Sid = sidValues[1]
    }
    return await next()
  } catch (error) {
    // 处理错误情况，返回错误信息
    ctx.body = { success: false, error: error.message }
  }
}

async function sendHarborLoginRequest() {
  try {
    const formData = new URLSearchParams()
    formData.append('principal', config.harbor.user)
    formData.append('password', config.harbor.password)
    // 使用 axios 发送登录请求
    const response = await axios.post(
      'http://registry.mengning.com.cn/c/login',
      formData
    )

    // 返回响应对象
    return response
  } catch (error) {
    // 捕获 403 错误
    if (error.response && error.response.status === 403) {
      // 从响应头中提取 X-Harbor-Csrf-Token 和 _gorilla_csrf
      xHarborCsrfToken = error.response.headers['x-harbor-csrf-token']
      const setCookieHeader = error.response.headers[
        'set-cookie'
      ].find(cookie => cookie.includes('_gorilla_csrf'))
      // 使用正则表达式匹配_gorilla_csrf=后和分号之前的字段，并去掉_gorilla_csrf=部分
      const matchResult = setCookieHeader.match(/_gorilla_csrf=([^;]+);/)

      // 如果匹配成功，获取捕获的内容
      gorillaCsrfValue = matchResult ? matchResult[1] : null
      const formData = new URLSearchParams()
      formData.append('principal', config.harbor.user)
      formData.append('password', config.harbor.password)
      // 将 X-Harbor-Csrf-Token 和 _gorilla_csrf 添加到下一个请求的 Cookie 中
      const nextResponse = await axios.post(
        'http://registry.mengning.com.cn/c/login',
        formData,
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Cookie: `_gorilla_csrf=${gorillaCsrfValue}`,
            'X-Harbor-Csrf-Token': xHarborCsrfToken,
          },
        }
      )

      // 返回下一个请求的响应对象
      return nextResponse
    }

    // 如果不是 403 错误，或者重试失败，抛出错误
    throw error
  }
}

const harborProjects = async ctx => {
  try {
    // 发送 GET 请求
    const response = await axios.get(
      'http://registry.mengning.com.cn/api/v2.0/projects',
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Cookie: `sid=${Sid}`,
        },
      }
    )
    // console.log(`print`, response)

    // 将响应存入 ctx.body
    ctx.body = response.data
  } catch (error) {
    // 处理请求错误
    console.error('Error:', error.message)
    ctx.body = 'Error occurred'
  }
}

const harborpubProjects = async ctx => {
  try {
    // 发送 GET 请求
    const response = await axios.get(
      'http://registry.mengning.com.cn/api/v2.0/projects/base/repositories',
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Cookie: `sid=${Sid}`,
        },
      }
    )

    // 将响应存入 ctx.body
    ctx.body = response.data
  } catch (error) {
    // 处理请求错误
    console.error('Error:', error.message)
    ctx.body = 'Error occurred'
  }
}

const harboruserProjects = async ctx => {
  try {
    // 从路由参数中提取工作区
    const workspace = ctx.params.workspace

    // 构建用于 GET 请求的新 URL
    const apiUrl = `http://registry.mengning.com.cn/api/v2.0/projects/${workspace}/repositories`

    // 发送 GET 请求
    const response = await axios.get(apiUrl, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Cookie: `sid=${Sid}`, // 请确保 Sid 已定义
      },
    })

    // 将响应存入 ctx.body
    ctx.body = {
      items: response.data.map(item => ({
        apiVersion: 'devops.kubesphere.io/v1alpha3',
        kind: 'DevOpsProject',
        metadata: {
          name: item.name,
          generateName: item.name.split('/')[1],
          creationTimestamp: item.creation_time,
          annotations: {
            'devopsproject.devops.kubesphere.io/syncstatus': 'successful',
            'kubesphere.io/creator': item.name.split('/')[0],
          },
          labels: {
            'kubesphere.io/workspace': item.name.split('/')[0],
          },
        },
      })),
      totalItems: response.data.length,
    }

    // ctx.body = response.data
  } catch (error) {
    // 处理请求错误
    console.error('Error:', error.message)
    ctx.body = 'Error occurred'
  }
}

const harborrobots = async ctx => {
  try {
    const workspace = ctx.params.workspace
    const harborRobotList = await harborrobotsview()
    const targetObject = harborRobotList.find(robot =>
      robot.permissions.some(
        permission => permission.namespace === `${workspace}`
      )
    )
    let robotid
    if (targetObject) {
      robotid = targetObject.id
      //   console.log("Namespace 'zmy' found with robotid:", robotid)
      await harborrobotdelete(robotid)
    }
    // 执行创建robot的操作
    const createResponse = await harborrobotcreate(workspace)
    ctx.body = createResponse
    return
  } catch (error) {
    // 处理请求错误
    console.error('print harborrobots Error:', error.message)
    ctx.body = 'Error occurred'
  }
}

async function harborrobotsview() {
  try {
    const apiUrl = `http://registry.mengning.com.cn/api/v2.0/robots`
    const response = await axios.get(apiUrl, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Cookie: `sid=${Sid}`, // 请确保 Sid 已定义
      },
    })
    const body = response.data
    return body
  } catch (error) {
    // 处理请求错误
    console.error('print Error:', error.message)
  }
}

async function harborrobotdelete(robotid) {
  const apiUrl = `http://registry.mengning.com.cn/api/v2.0/robots/${robotid}`
  const response = await axios.delete(apiUrl, {
    headers: {
      // 'Content-Type': 'application/x-www-form-urlencoded',
      Cookie: `_gorilla_csrf=${gorillaCsrfValue};sid=${Sid}`,
      'X-Harbor-Csrf-Token': xHarborCsrfToken,
    },
  })
  return response
}

async function harborrobotcreate(workspace) {
  const jsonData = {
    name: `${workspace}`,
    duration: -1,
    description: null,
    disable: false,
    level: 'system',
    permissions: [
      {
        kind: 'project',
        namespace: `${workspace}`,
        access: [
          { resource: 'repository', action: 'list' },
          { resource: 'repository', action: 'pull' },
          { resource: 'repository', action: 'push' },
          { resource: 'repository', action: 'delete' },
          { resource: 'artifact', action: 'read' },
          { resource: 'artifact', action: 'list' },
          { resource: 'artifact', action: 'delete' },
          { resource: 'artifact-label', action: 'create' },
          { resource: 'artifact-label', action: 'delete' },
          { resource: 'tag', action: 'create' },
          { resource: 'tag', action: 'delete' },
          { resource: 'tag', action: 'list' },
          { resource: 'scan', action: 'create' },
          { resource: 'scan', action: 'stop' },
        ],
      },
    ],
  }
  const apiUrl = `http://registry.mengning.com.cn/api/v2.0/robots`
  const createResponse = await axios.post(apiUrl, jsonData, {
    headers: {
      'Content-Type': 'application/json',
      Cookie: `_gorilla_csrf=${gorillaCsrfValue};sid=${Sid}`,
      'X-Harbor-Csrf-Token': xHarborCsrfToken,
    },
  })
  return createResponse.data
}

const createProjects = async ctx => {
  try {
    const workspace = ctx.params.workspace
    const createResponse = await createProject(workspace)
    ctx.body = createResponse
  } catch (error) {
    // 处理请求错误
    console.error('create project error:', error.message)
    ctx.body = 'Error occurred'
  }
}

async function createProject(workspace) {
  const jsonData = {
    project_name: `${workspace}`,
    metadata: {
      public: 'false',
    },
    storage_limit: 21474836480,
    registry_id: null,
  }
  const apiUrl = `http://registry.mengning.com.cn/api/v2.0/projects`
  const createProjectResponse = await axios.post(apiUrl, jsonData, {
    headers: {
      'Content-Type': 'application/json',
      Cookie: `_gorilla_csrf=${gorillaCsrfValue};sid=${Sid}`,
      'X-Harbor-Csrf-Token': xHarborCsrfToken,
    },
  })
  return createProjectResponse.data
}

const deleteProjects = async ctx => {
  try {
    const name = ctx.params.name
    const workspace = ctx.params.workspace
    const deleteResponse = await deleteProject(name, workspace)
    ctx.body = deleteResponse // You might want to set ctx.body to the response data if needed.
  } catch (error) {
    // 处理请求错误
    console.error('delete project error:', error.message)
    ctx.body = 'Error occurred'
  }
}

async function deleteProject(name, workspace) {
  const apiUrl = `http://registry.mengning.com.cn/api/v2.0/projects/${workspace}/repositories/${name}`
  const deleteProjectResponse = await axios.delete(apiUrl, {
    headers: {
      'Content-Type': 'application/json',
      Cookie: `_gorilla_csrf=${gorillaCsrfValue};sid=${Sid}`,
      'X-Harbor-Csrf-Token': xHarborCsrfToken,
    },
  })
  return deleteProjectResponse.data
}

module.exports = {
  harborLogin,
  harborProjects,
  harborpubProjects,
  harboruserProjects,
  harborrobots,
  createProjects,
  deleteProjects,
}
